<template>
  <div class="wrapper">
    <div v-for="(col, idx) in colCollect" :key="idx"  :style="{'width': (GOAL_WIDTH+92) + 'px', 'min-width': (GOAL_WIDTH+92) + 'px', 'position': 'relative'}">
      <Item :goalHeight="item.taskDatatype==='2' ? GOAL_HEIGHT : SUB_GOAL_HEIGHT" :goalWidth="GOAL_WIDTH" :goalOffset="GOAL_GOAL_TOP_OFFSET" @openChild="openChild" @closeChild="closeChild" @openTaskDetail="openTaskDetail" @addSubTask="addSubTask" v-for="(item, index) in col" :key="item.id" :goal="item" :index="index"/>
    </div>
  </div>
</template>

<script>
import Item from './item'
import formUtil from "@/utils/formUtil";

export default {
  data() {
    return {
      GOAL_HEIGHT: 100, //目标高度
      GOAL_WIDTH: 340, //目标宽度
      SUB_GOAL_HEIGHT: 68, //子任务高度
      GOAL_GOAL_TOP_OFFSET: 20, //目标与目标高度间距
      colCollect: [],
      goalBelongIds: [],
      goalListInit: [],
    }
  },
  components: {
    Item
  },
  props: ["taskList"],
  mounted() {
    this.getGoalList()
  },
  watch :{
    taskList: {
      handler: function(newVal, oldVal) {
        this.getGoalList();
      },
      deep: true
    }
  },
  methods: {
    addSubTask(data) {
      this.$emit("addSubTask", data)
    },
    openTaskDetail(id) {
      this.$emit("openTaskDetail", id);
    },
    objSort(prop){
      return function (obj1, obj2) {
        var val1 = obj1[prop];
        var val2 = obj2[prop];
        if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
          val1 = Number(val1);
          val2 = Number(val2);
        }
        if (val1 < val2) {
          return -1;
        } else if (val1 > val2) {
          return 1;
        } else {
          return 0;
        }           
      }
    },
    async getGoalList() {
      this.colCollect = [];
      let goalList = JSON.parse(JSON.stringify(this.taskList));
      goalList.reverse().sort(this.objSort("taskEndTime"))
      this.goalBelongIds = goalList.map(x => {return x.taskBelongId})
      var data = [];
      goalList.forEach((goal, index) => {
        goal.belongId = goal.taskBelongId
        goal.top = 0
        goal.left = 0
        goal.topgoal = 0
        goal.drawTopLine = false
        goal.height = 0
        goal.row = 1
        goal.goalChain = (index + 1).toString()
        if(this.goalBelongIds.includes(goal.id)) {
          goal.hasChild = true;
          goal.show = false;
        }
        data.push(goal)
      })
      this.goalListInit = JSON.stringify(data);
      let list = data.filter(goal => {
        return goal.taskDatatype === '2'
      })
      this.colCollect.push(list);
      this.computedGoalAndKrHeight();
    },
    openAllChild() {
      for(let i = 0; i < this.colCollect.length; i++){
        this.colCollect[i].forEach(goal => {
          if(goal.hasChild) this.openChild(goal)
        })
      }
      this.computedGoalAndKrHeight();
    },
    async openChild(goal) {
      let goalIdx = this.colCollect[goal.row - 1].findIndex((item) => item.id === goal.id);
      let combineChain = goal.goalChain;
      let row = goal.row + 1;
      this.colCollect[goal.row - 1][goalIdx].show = true;

      JSON.parse(this.goalListInit).forEach((element, index) => {
        let newObj = {}
        if (element.belongId === goal.id) {
          element.row = row
          element.left = 0
          element.combineChain = combineChain + '-' + index
          newObj = element
          this.colCollect[row-1] ? this.colCollect[row-1].push(newObj) : this.colCollect.push([newObj])
        }
      })
      this.computedGoalAndKrHeight();
    },
    closeChild(goal) {
      let goalIdx = this.colCollect[goal.row - 1].findIndex((item) => item.id === goal.id);
      let combineChain = `${goal.combineChain? goal.combineChain + '-': ''}${goal.goalChain}`;
      this.colCollect[goal.row - 1][goalIdx].show = false;
      
      //删除
      this.colCollect.forEach((col, idx) => {
        let newCol = col.filter((goal) => {
          if(goal.combineChain) {
            return goal.combineChain.indexOf(combineChain) !== 0
          }else {
            return true
          }
        })
        this.$set(this.colCollect, idx, newCol)
      })
      this.computedGoalAndKrHeight();
    },
    /**
     * 从左向右根据链路、goal高度、kr高度计算所有goal、kr的位置
     */
    computedChainPosition() {
      for(let i = 0; i < this.colCollect.length; i++){
        this.colCollect[i].forEach((goal, idx) => {
          if(i !== 0 && goal.belongId) {
            let chainArr = goal.combineChain.split('-');
            this.colCollect[i-1].forEach((element, index) => {
              if(element.goalChain === chainArr[chainArr.length - 2]) {
                goal.top = this.colCollect[i-1][index].top + (this.GOAL_HEIGHT - this.SUB_GOAL_HEIGHT)/2;
              }
            })

            if(this.colCollect[i][idx - 1] && this.colCollect[i][idx - 1].belongId === goal.belongId) {
              goal.top = this.colCollect[i][idx - 1].top + this.colCollect[i][idx - 1].height + this.GOAL_GOAL_TOP_OFFSET;
              //记录前一行的goal高度用来划线使用
              goal.topgoal = this.colCollect[i][idx - 1].top;
              goal.drawTopLine = true
            }
          }

          //第一列第二个及以后的goal计算位置 (实际应该不需要，只有一个总目标)
          if(i === 0 && idx !== 0) {
            goal.top = this.colCollect[i][idx - 1].height + this.colCollect[i][idx - 1].top + this.GOAL_GOAL_TOP_OFFSET;
          }
        })
      }
    },
    /**
     * 从右向左计算kr高度、goal高度
     */
    computedGoalAndKrHeight() {
      this.resetAllGoalAndKrHeight();
      //遍历列数
      for(let i = this.colCollect.length - 1; i >= 0; i--){
        this.colCollect[i].forEach((goal, idx) => {
          if(goal.belongId && i !== 0) {
            let chainArr = goal.combineChain.split('-');
            let goalChain = chainArr[chainArr.length - 2];
            this.colCollect[i-1].forEach((element, index) => {
              if(element.goalChain === goalChain) this.colCollect[i-1][index].height += goal.height + this.GOAL_GOAL_TOP_OFFSET;
            })
          }
          if(i === 0 && (goal.height > this.GOAL_HEIGHT)) goal.height = goal.height > 2*this.GOAL_HEIGHT ? (goal.height-this.GOAL_HEIGHT) : this.GOAL_HEIGHT
        })
      }
      this.computedChainPosition()
    },
    /**
     * 重置所有高度：当节点变化的时候，高度会发生变化，先重置后重新计算
     */
    resetAllGoalAndKrHeight() {
      this.colCollect.forEach(col => {
        col.forEach(goal => {
          goal.height = goal.taskDatatype==='2' ? this.GOAL_HEIGHT : this.SUB_GOAL_HEIGHT;
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.wrapper::-webkit-scrollbar {/*滚动条整体样式*/
  width: 4px;     /*高宽分别对应横竖滚动条的尺寸*/
  height: 4px;
  scrollbar-arrow-color:red;
}
.wrapper::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
  border-radius: 5px;
  box-shadow: inset 0 0 5px #DEDEDE;
  background: rgba(0,0,0,0.2);
  scrollbar-arrow-color:red;
}
.wrapper::-webkit-scrollbar-track {/*滚动条里面轨道*/
  box-shadow: inset 0 0 5px #F5F5F5;
  border-radius: 0;
  background: rgba(0,0,0,0.1);
}
.wrapper{
  width:100%;
  padding: 20px 100px;
  overflow: auto;
  background: #F6F6F6;
  display: flex;
}
</style>